#include<iostream>

#include <memory>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cerrno>
#include<signal.h>
#include <stdlib.h>
#include <cstring>
#include<unistd.h>
#include<cassert>

//./tcp_client targetIP targetPort

static void usage(std::string proc)
{
    std::cout<<"\nUsage: "<<proc<<" SeverIP SeverPort\n"<<std::endl;
}
int main(int argc,char* argv[])
{
    if(argc!=3)
    {
        usage(argv[0]);
        exit(1);
    }
    std::string server_ip=argv[1];
    uint16_t server_port=atoi(argv[2]);
    
    int sock=socket(AF_INET,SOCK_STREAM,0);
    if(sock<0)
    {
        std::cerr<<"socket error"<<std::endl;        
        exit(2);
    }
    //client不要显式绑定，让OS自己选择
    //需要链接别人的能力,connect会自动绑定端口
    struct sockaddr_in server;
    memset(&server,0,sizeof(server));
    server.sin_port=htons(server_port);
    server.sin_family=AF_INET;
    server.sin_addr.s_addr=inet_addr(server_ip.c_str());
    if(connect(sock,(struct sockaddr*)&server,sizeof(server))<0)
    {
        std::cerr<<"connect error "<<std::endl;
        exit(3);
    }
    //连接成功
    std::cout<<"connect sucess"<<std::endl;
    while(true)
    {
        char buffer[1024];
        std::string line;
        std::cout<<"please input your information:->";
        std::getline(std::cin,line);
        send(sock,line.c_str(),line.size(),0);
        ssize_t s=recv(sock,buffer,sizeof(buffer)-1,0);
        if(s>0)
        {
            buffer[s]=0;
            std::cout<<"server 回显#: "<<buffer<<std::endl;
        }
        else
        {
            break;
        }
    }
    close(sock);
    return 0;
}